package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImp implements OrderService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    @Transactional
    public OrderSubmitVO addOrder(OrdersSubmitDTO ordersSubmitDTO) {
        Orders orders=new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);

        AddressBook addressBook = addressBookMapper.getById(orders.getAddressBookId());
        if(addressBook==null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        Long userId=BaseContext.getCurrentId();
        ShoppingCart shoppingCart=new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if(list==null||list.size()==0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //向订单插入1条数据
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress(addressBook.getFullAddress());
        orders.setUserId(userId);

        orderMapper.insert(orders);

        List<OrderDetail> orderDetailList=new ArrayList<>();
        //订单详情擦入n条
        for (ShoppingCart cart:list){
            OrderDetail orderDetail=new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);
        //清空用户购物车数据

        shoppingCartMapper.clean(userId);
        //封装vo返回结果
        OrderSubmitVO build = OrderSubmitVO.builder()
                .orderAmount(orders.getAmount())
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();

        return build;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

// 为替代微信支付成功后的数据订单状态更新
        Integer OrderStatus = Orders.PAID; // 支付状态：已支付
        Integer Status = Orders.TO_BE_CONFIRMED; // 订单状态：待接单
        LocalDateTime check_out_time = LocalDateTime.now ();

// 获取订单号码
        String orderNumber = ordersPaymentDTO.getOrderNumber();


        log.info("调用 updateStatus，用于替换微信支付更新数据库状态的问题");
        orderMapper.updateStatus(OrderStatus, Status, check_out_time, orderNumber);

        Map map=new HashMap<>();
        map.put("type",1);
        map.put("orderId",orderMapper.getByNumber(orderNumber).getId());
        map.put("content","订单号："+orderNumber);
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 得到历史订单
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult getHistoryOrders(OrdersPageQueryDTO ordersPageQueryDTO) {

        // 这行代码是关键：告诉 PageHelper 接下来的查询需要分页
        PageHelper.startPage(
                ordersPageQueryDTO.getPage(),// 页码（从1开始）
                ordersPageQueryDTO.getPageSize() // 每页条数
        );
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        Page<Orders> page= orderMapper.pageQuery(ordersPageQueryDTO);
        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id
                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);
                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }

    @Override
    public void cancelOrders(OrdersCancelDTO ordersCancelDTO) {
        Orders orders=new Orders();
        orders.setStatus(Orders.CANCELLED);
        orders.setId(ordersCancelDTO.getId());
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public OrderVO getOrdersWithDetail(Long id) {
        Orders orders=orderMapper.getById(id);
        if (orders == null) {
            // 记录日志，方便排查问题
            log.error("查询订单详情失败：订单id={}不存在", id);
            // 抛出异常，由上层（如Controller）统一处理
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        List<OrderDetail> orderDetail=orderDetailMapper.getByOrderId(orders.getId());
        OrderVO orderVO=new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetail);
        return orderVO;
    }

    /**
     * 根据id再来一单
     * @param id
     */
    @Transactional
    public void getSameOne(Long id) {
        Orders originalOrder = orderMapper.getById(id);
        if (originalOrder == null) {
            throw new RuntimeException("原订单不存在");
        }

        // 2. 复制原订单信息，重置必要字段
        Orders newOrder = new Orders();
        // 复制原订单的业务字段（用户ID、地址、金额等）
        BeanUtils.copyProperties(originalOrder, newOrder);

        // 3. 重置关键字段（避免冲突和数据错误）
        newOrder.setId(null); // 重置id，让数据库自增新主键
        newOrder.setNumber(generateNewOrderNumber());
        newOrder.setOrderTime(LocalDateTime.now()); // 新订单的下单时间
        newOrder.setStatus(Orders.PENDING_PAYMENT); // 新订单状态应为“待付款”（原代码设为PAID不合理）
        newOrder.setPayStatus(Orders.UN_PAID); // 未支付
        newOrder.setDeliveryTime(LocalDateTime.now().plusHours(1)); // 预计送达时间
        // 重置冗余字段
        newOrder.setCheckoutTime(null);
        newOrder.setCancelTime(null);
        newOrder.setCancelReason(null);
        newOrder.setRejectionReason(null);
        newOrder.setDeliveryTime(null); // 送达时间暂未发生，设为null

        // 4. 插入新订单，获取新订单的id（需确保mapper.insert能返回自增id）
        orderMapper.insert(newOrder);
        Long newOrderId = newOrder.getId(); // 若使用MyBatis，需在mapper.xml中配置useGeneratedKeys="true" keyProperty="id"

        // 5. 处理订单明细：复制原明细，关联新订单id
        List<OrderDetail> originalDetails = orderDetailMapper.getByOrderId(id); // 用原订单id查明细
        List<OrderDetail> newDetails = new ArrayList<>();
        for (OrderDetail originalDetail : originalDetails) {
            OrderDetail newDetail = new OrderDetail();
            BeanUtils.copyProperties(originalDetail, newDetail);
            newDetail.setId(null); // 重置明细id
            newDetail.setOrderId(newOrderId); // 关联新订单id
            newDetails.add(newDetail);
        }

        // 6. 批量插入新明细
        if (!newDetails.isEmpty()) {
            orderDetailMapper.insertBatch(newDetails);
        }
    }

    //TOdo
    @Override
    public PageResult getStatisticsNumbers() {

        return null;
    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 开启分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        // 注意：删除用户ID设置，管理端无需限定用户
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList<>();

        // 遍历订单，转换为OrderVO（包含菜品字符串）
        if (!CollectionUtils.isEmpty(page.getResult())) {
            for (Orders orders : page) {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);

                // 直接查询明细并转换为字符串（删除冗余查询）
                String orderDishes = orderDetailMapper.getByOrderId(orders.getId()).stream()
                        .map(detail -> detail.getName() + "*" + detail.getNumber() + ";")
                        .collect(Collectors.joining());

                orderVO.setOrderDishes(orderDishes);
                list.add(orderVO);
            }
        }

        return new PageResult(page.getTotal(), list);
    }

    @Override
    public void statusChange(OrdersConfirmDTO ordersConfirmDTO) {
        Long id=ordersConfirmDTO.getId();
        Integer status=ordersConfirmDTO.getStatus();
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND); // 自定义异常，前端接收“订单不存在”提示
        }

        log.info("原来的订单数据：{}",orders);
        log.info("传进来的参数：{}",ordersConfirmDTO);
        // 2. 校验订单当前状态是否允许流转（只能从“已接单”→“派送中”）
        if (!Objects.equals(orders.getStatus(), status-1)) {
            throw new OrderBusinessException("当前订单状态无法进行下一步操作");
        }

        Orders updateOrder = new Orders();
        updateOrder.setId(id);
        updateOrder.setStatus(status); // 状态4：派送中
        if(status==5){
            updateOrder.setDeliveryTime(LocalDateTime.now());
        }
        orderMapper.update(updateOrder);
    }

    @Override
    public void rejectOrder(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders=new Orders();
        orders.setStatus(Orders.CANCELLED);
        orders.setId(ordersRejectionDTO.getId());
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public void reminder(Long id) {
        Orders orders=orderMapper.getById(id);

        if(orders==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map<String,String> map=new HashMap<>();
        map.put("type","2");
        map.put("orerId",id.toString());
        map.put("content","订单号："+orders.getNumber());
        log.info("通过websocket向客户端浏览器推送催单信息：{}",map);
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }


    private String generateNewOrderNumber() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))
                + RandomStringUtils.randomNumeric(4);
    }
}
